package com.hfb.mashibing.alip8.juc.c016;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * synchronized 优化
 * ① 锁的细化：同步代码块中的语句，越少越好
 * ② 锁的粗化:
 */
public class FineCoarseLock {
    int count  = 0;

    synchronized void m() {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        count ++;

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < 10_000; i++)  count ++;
    }
    void n() {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        synchronized (this) {
            count ++;
        }

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < 10_000; i++)  count ++;
    }
    
    public static void main(String[] args) {
        final FineCoarseLock t = new FineCoarseLock();

        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            threads.add(new Thread(t::m, " thread - " + i));
        }

        threads.forEach((o) ->o.start());

        threads.forEach((o) ->{
            try {
                o.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println(t.count);
    }
}
